﻿using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Configuration;
using WT.OpenIddict.Domain.Shared.LifeTime;

namespace WT.OpenIddict.Application.Email;

public class SendEmailManager : ITransientDependency
{
    private const string _openiddictMngObjName = "test/openid.png";


    public SendEmailManager(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; set; }


    public async Task SendEmailAsync(string email, string title, string content)
    {
        var smtpServer = Configuration["Email:SmtpServer"];
        var port = int.Parse(Configuration["Email:Port"]);
        var enableSsl = bool.Parse(Configuration["Email:EnableSsl"]);
        var userName = Configuration["Email:UserName"];
        var password = Configuration["Email:Password"];
        var from = Configuration["Email:From"];
        var displayName = Configuration["Email:DisplayName"];

        var message = new MailMessage();
        message.From = new MailAddress(from, displayName);
        message.To.Add(email); // 用 email
        message.Subject = title; // 用 title
        message.Body = content; // 用 content
        message.IsBodyHtml = true;

        using (var client = new SmtpClient(smtpServer, port))
        {
            client.EnableSsl = enableSsl;
            client.Credentials = new NetworkCredential(userName, password);
            await client.SendMailAsync(message);
        }
    }

    public async Task SendVertifyCodeEmail(string email, string code)
    {
        // 获取 logo 临时地址
        // var logoUrl = await _aliossManager.GetTempUrlAsync(_openiddictMngObjName);
        var logoUrl = string.Empty;

        // 邮件主题
        var title = "重置密码";

        // 邮件正文（HTML格式，带logo和说明）
        var content = $@"
        <div style='font-family:Arial,sans-serif;max-width:500px;margin:auto;padding:20px;border-radius:8px;border:1px solid #eee;'>
            <div style='text-align:center;margin-bottom:20px;'>
                <img src='{logoUrl}' alt='logo' style='height:60px;' />
            </div>
            <h2 style='color:#2da44e;'>您的验证码</h2>
            <p style='font-size:18px;letter-spacing:2px;'><b>{code}</b></p>
            <p>请在5分钟内输入此验证码完成操作。</p>
            <p style='color:#888;font-size:13px;'>如果不是您本人操作，请忽略此邮件。</p>
        </div>
    ";

        await SendEmailAsync(email, title, content);
    }
}